package com.blog.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.lang.Singleton;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.IdentifierGenerator;

import java.io.Serializable;

/**
 * @author: chengqiang
 * @date: 2018/12/6 13:28
 * hibernate 自定义ID生成策略
 */
@Slf4j
public class IdGen implements IdentifierGenerator, Serializable {

    @Override
    public Serializable generate(SharedSessionContractImplementor sharedSessionContractImplementor, Object o) throws HibernateException {
        return nextID();
    }

    public static Long nextID() {
       Snowflake snowflake = Singleton.get(Snowflake.class, 1l, 1l);
        return snowflake.nextId();
    }

    public static void main(String[] args) {
        TimeInterval timer = DateUtil.timer();
        timer.start();
        for (int i = 0; i < 1000000; i++) {
            Long id = nextID();
            log.info("{}", id);
        }
        Long time = timer.interval();
        log.info("耗时:{}毫秒", time);
    }
}
